/*************************************************************************
	> File Name: udp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/01 22:20
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cerrno>
#include <cstring>
#include "thread.hpp"
#include <cassert>
#include <memory>

const int BUF_SIZE = 1024;

uint16_t port;
std::string ip;

static void usage(std::string proc)
{
    std::cout << "Usage:" << proc << " ip port." << std::endl;
}

static void* udpSend(void* args)
{
    int sock = *(int*)((ThreadData*)args)->_args;
    std::string name = ((ThreadData*)args)->_name;
    struct sockaddr_in server;
    std::string message;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    while (1) {
        std::cout << "Input your message:" << std::endl;
        std::getline(std::cin, message);
        if ("quit" == message) {
            break;
        }
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof server);
    }
    return nullptr;
}

static void* udpRecv(void *args)
{
    int sock = *(int*)((ThreadData*)args)->_args;
    std::string name = ((ThreadData*)args)->_name;
    char buffer[BUF_SIZE];
    while (1) {
        memset(buffer, 0, sizeof buffer);
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        ssize_t s = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr*)&temp, &len);
        if (s > 0) {
            std::cout << buffer << std::endl;
        }
    }
    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    port = atoi(argv[2]);
    ip = argv[1];
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    std::unique_ptr<Thread> sender(new Thread(1, udpSend, (void*)&sock));
    std::unique_ptr<Thread> recver(new Thread(2, udpRecv, (void*)&sock));
    sender->start();
    recver->start();
    sender->join();
    recver->join();
    return 0;
}
